const fs = require('fs')
const path = require('path')
const { getSuffix, getVideoDuration } = require('./utils/util')

// a. 读取指定目录下的所有文件
const arr = fs.readdirSync(path.join(__dirname, './video'))
// b. 处理文件
const promises = arr.map(async (item, index) => {
  // 1. 根据序号计算出id，获取后缀
  const id = index + 1, suffix = getSuffix(item)
  const obj = { id: id, name: item, duration: 0 }
  // 2. 获取视频时长
  const videoDir = path.join(__dirname, `./video/${item}`)
  const duration = await getVideoDuration(videoDir)
  obj.duration = duration
  // 3. 重命名视频文件名
  fs.renameSync(videoDir, path.join(__dirname, `./video/${id}.${suffix}`))
  return obj
})
// 3. 将结果生成到category.json文件中
Promise.all(promises).then(res => {
  fs.writeFileSync(path.join(__dirname, './category.json'), JSON.stringify(res, null, 2))
})
